package com.zsc.yygh.security.controller;

import cn.hutool.core.util.IdUtil;
import com.wf.captcha.base.Captcha;
import com.zsc.yygh.common.exception.YyghException;
import com.zsc.yygh.common.result.Result;
import com.zsc.yygh.security.config.bean.LoginCodeEnum;
import com.zsc.yygh.security.config.bean.LoginProperties;
import com.zsc.yygh.security.entity.dto.AuthUserDto;
import com.zsc.yygh.user.client.PatientFeignClient;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin/auth")
public class AuthorizationController {

    @Resource
    private LoginProperties loginProperties;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private PatientFeignClient patientFeignClient;

    @PostMapping(value = "/login")
    public Result login(@RequestBody AuthUserDto authUser){

        String code = redisTemplate.opsForValue().get(authUser.getUuid());
        redisTemplate.delete(authUser.getUuid());

        if(StringUtils.isBlank(code)){
            throw new YyghException("验证码不存在或已过期",201);
        }

        if (StringUtils.isBlank(authUser.getCode()) || !authUser.getCode().equalsIgnoreCase(code)) {
            throw new YyghException("验证码错误",210);
        }

        //查询用户和密码
        Result result = patientFeignClient.checkUsernameAndPassword(authUser.getUsername(), authUser.getPassword());
        if(!result.isOk()){
            throw new YyghException("用户名或密码错误",210);
        }
        String token = authUser.getUsername();
        return Result.ok(token);
    }

    @ApiOperation("获取验证码")
    @GetMapping(value = "/code")
    public Result getCode() {
        // 获取运算的结果
        Captcha captcha = loginProperties.getCaptcha();
        String uuid = IdUtil.simpleUUID();
        //当验证码类型为 arithmetic时且长度 >= 2 时，captcha.text()的结果有几率为浮点型
        String captchaValue = captcha.text();
        if (captcha.getCharType() - 1 == LoginCodeEnum.arithmetic.ordinal() && captchaValue.contains(".")) {
            captchaValue = captchaValue.split("\\.")[0];
        }
        // 保存到redis中
        redisTemplate.opsForValue().set(uuid,captchaValue, loginProperties.getLoginCode().getExpiration(), TimeUnit.MINUTES);
        //redisUtils.set(uuid, captchaValue, loginProperties.getLoginCode().getExpiration(), TimeUnit.MINUTES);
        // 验证码信息
        Map<String, Object> imgResult = new HashMap<String, Object>(2) {{
            put("img", captcha.toBase64());
            put("uuid", uuid);
        }};
        return Result.ok(imgResult);
    }

}
